<template>
  <div class="feature-version__container">
    <div class="table-panel">
      <resource-table
        ref="refResourceTable"
        v-loading="ifLoading"
        :table-columns="tableColumns"
        :showSelection="true"
        operations="edit,delete"
        :operation-column-width="160"
        @queryTable="getList"
        @selectionChange="rowSelectionChange"
      >
        <template #headerLeft>
          <div class="btn-list">
            <div class="btn-item btn-add" style="width: 100px">
              <el-button v-waves type="primary" style="width: 100px" @click="handlerAddNew">
                新增
              </el-button>
            </div>
            <div class="btn-item btn-add-batch" style="width: 100px; margin-left: 10px">
              <el-button v-waves type="primary" style="width: 100px" @click="handlerImportData">
                导入
              </el-button>
            </div>
            <div
              v-show="rowsSelected.length > 1"
              class="btn-item btn-delete-batch"
              style="width: 100px; margin-left: 10px"
            >
              <el-button v-waves type="danger" style="width: 100px" @click="handlerDeleteBatch">
                批量删除
              </el-button>
            </div>
          </div>
        </template>
        <template #headerRight="props">
          <div class="filter-conditions">
            <!-- <div class="filter-item">
              申请时间：
              <el-date-picker
                v-model="props.queryParameters.timeRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                @change="handlerClear"
              >
              </el-date-picker>
            </div>-->
            <div class="filter-item" style="margin-left: 10px">
              业务类型：
              <el-input
                placeholder="请输入业务类型"
                size="small"
                style="width: 170px"
                v-model="props.queryParameters.businessType"
                clearable
                @keyup.native="() => handlerInputValueChange('businessType')"
                @clear="() => handlerClear('businessType')"
              >
              </el-input>
              <!-- <el-select
                v-model="props.queryParameters.businessType"
                size="small"
                style="width: 170px"
                placeholder="请输入业务类型"
                clearable
                @clear="handlerClear"
              >
                <el-option
                  v-for="item in businessTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select> -->
            </div>
            <div class="filter-item" style="margin-left: 10px">
              要素名称：
              <el-input
                placeholder="请输入要素名称"
                size="small"
                style="width: 170px"
                v-model="props.queryParameters.featureCName"
                clearable
                @keyup.native="() => handlerInputValueChange('featureCName')"
                @clear="() => handlerClear('featureCName')"
              >
              </el-input>
              <!-- <el-select
                v-model="props.queryParameters.featureName"
                size="small"
                style="width: 170px"
                placeholder="请输入要素名称"
                clearable
                @clear="handlerClear"
              >
                <el-option
                  v-for="item in featureNameOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select> -->
            </div>
            <div class="filter-item" style="margin-left: 10px">
              版本名称：
              <el-input
                placeholder="请输入版本名称"
                size="small"
                style="width: 170px"
                v-model="props.queryParameters.versionCName"
                clearable
                @keyup.native="() => handlerInputValueChange('versionCName')"
                @clear="() => handlerClear('versionCName')"
              >
              </el-input>
              <!-- <el-select
                v-model="props.queryParameters.featureVersion"
                size="small"
                style="width: 170px"
                placeholder="请输入要素版本"
                clearable
                @clear="handlerClear"
              >
                <el-option
                  v-for="item in featureVersionOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select> -->
            </div>
            <div class="filter-item" style="margin-left: 10px">
              字段别名：
              <el-input
                placeholder="请输入字段别名："
                size="small"
                style="width: 170px"
                v-model="props.queryParameters.fieldAlias"
                clearable
                @keyup.native="() => handlerInputValueChange('fieldAlias')"
                @clear="() => handlerClear('fieldAlias')"
              >
              </el-input>
              <!-- <el-select
                v-model="props.queryParameters.fieldAlias"
                size="small"
                style="width: 170px"
                placeholder="请输入字段名称"
                clearable
                @clear="handlerClear"
              >
                <el-option
                  v-for="item in fieldAliasOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select> -->
            </div>
          </div>
        </template>
        <template #operation="props">
          <el-tooltip class="col-btn-icon" effect="dark" content="修改" placement="top">
            <el-button
              type="text"
              @click="handlerModify(props.rowInfo)"
              icon="el-icon-edit"
              style="font-size: 15px; color: #67c23a"
            ></el-button>
          </el-tooltip>
          <el-tooltip class="col-btn-icon" effect="dark" content="删除" placement="top">
            <el-button
              type="text"
              @click="handlerDelete(props.rowInfo)"
              icon="el-icon-delete"
              style="font-size: 15px; color: #f56c6c"
            ></el-button>
          </el-tooltip>
          <el-tooltip class="col-btn-icon" effect="dark" content="数据标准版本" placement="top">
            <el-button
              type="text"
              size="mini"
              icon="el-icon-s-management"
              @click="handlerFeatureVersionManage(props.rowInfo)"
              style="font-size: 15px; color: #409eff"
            >
            </el-button>
          </el-tooltip>
        </template>
      </resource-table>
    </div>
    <!-- 数据库信息窗口 -->
    <el-dialog
      :title="formDialogTitle"
      :center="true"
      :visible.sync="formDialogVisible"
      :close-on-click-modal="false"
      class="form-dialog"
      width="40%"
      height="40%"
    >
      <el-form :ref="refFormName" :model="form" :rules="formRules" label-width="100px">
        <el-form-item label-width="0">
          <el-col :span="12">
            <el-form-item label="要素版本" prop="featureVersionId">
              <el-select
                v-model="form.featureVersionId"
                placeholder="请选择要素版本"
                class="form-item"
                remote
                filterable
                :remote-method="remoteGetVersionsOptions"
                @change="handlerVersionChange"
              >
                <el-option
                  v-for="item in featureVersionOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="字段值出处" prop="docStandard">
              <el-select
                v-model="form.docStandard"
                placeholder="请选择字段出处"
                class="form-item"
                clearable
              >
                <el-option
                  v-for="item in docStandardOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label-width="0">
          <el-col :span="12">
            <el-form-item label="顺序号" prop="domainOrder">
              <el-input
                v-model="form.domainOrder"
                placeholder="请输入顺序号"
                @keyup.native="
                  (e) => {
                    checkIFNum('domainOrder', form.domainOrder);
                  }
                "
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="字段名" prop="fieldName">
              <el-select v-model="form.fieldName" placeholder="请选择字段名" class="form-item">
                <el-option
                  v-for="item in fieldAliasOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label-width="0">
          <el-col :span="12">
            <el-form-item label="编码-Key" prop="key">
              <el-input v-model="form.key" placeholder="请输入编码-Key"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="名称-Value" prop="value">
              <el-input v-model="form.value" placeholder="请输入名称-Value"></el-input>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="备注" prop="desc">
          <el-input
            v-model="form.desc"
            type="textarea"
            placeholder="请输入备注"
            :rows="4"
          ></el-input>
        </el-form-item>
        <el-form-item label-width="0">
          <div style="width: 100%; text-align: center">
            <el-button type="primary" @click="handlerSubmit(refFormName)">确定</el-button>
            <el-button @click="handlerCancel(refFormName)">取消</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 上传组件 -->
    <div class="upload-container" v-show="false">
      <el-upload
        :ref="refUploadFile"
        class="upload-demo"
        :action="upload.url"
        :limit="upload.limit"
        :accept="upload.accept"
        :file-list="upload.fileList"
        :before-remove="uploadFileBeforeRemove"
        :on-remove="uploadFileRemove"
        :on-exceed="uploadFileExceed"
        :before-upload="uploadBeforeFile"
        :on-success="uploadFileSuccess"
        :on-change="uploadFileStateChange"
        :http-request="httpUpload"
      >
        <el-button ref="refUploadButton" size="small" type="primary">点击上传</el-button>
        <div slot="tip" class="el-upload__tip">
          只能上传 .excel 文件，且不超过 {{ upload.maxFielSize_M }}M
        </div>
      </el-upload>
    </div>
  </div>
</template>

<script>
import * as moment from 'moment';
import waves from '@/directive/waves';
import { pageList, addOne, updateOne, deleteOne ,importBatchData} from '@/api/data-standard/fieldDomain';
import { pageList as versionList } from '@/api/data-standard/featureVersion';
import { pageList as fieldList } from '@/api/data-standard/field';
import { pageList as standardDocsList } from '@/api/data-standard/standardDocs';

export default {
  name: 'FeatureVersion',
  components: {},
  directives: {
    waves,
  },
  data() {
    return {
      // 表格这遮罩
      ifLoading: false,
      // 业务类型
      businessTypeOptions: [
        {
          label: '常规监测',
          value: 'CGJC',
        },
        {
          label: '督察执法',
          value: 'DCZF',
        },
        {
          label: '用地审批',
          value: 'YDSP',
        },
        {
          label: '现状调查',
          value: 'XZDC',
        },
      ],
      // 要素名称
      featureNameOptions: [
        {
          label: '常规监测图斑',
          value: 'CGJCTB',
          pId: 'CGJC',
        },
        {
          label: '卫片执法国家下发图斑',
          value: 'WPZF_GJXFTB',
          pId: 'DCZF',
        },
        {
          label: '中间征地',
          value: 'TDZS_ZJK',
          pId: 'YDSP',
        },
        {
          label: '成果征地',
          value: 'TDZS_CGK',
          pId: 'YDSP',
        },
        {
          label: '地类图斑',
          value: 'DLTB',
          pId: 'XZDC',
        },
      ],
      // 要素版本
      featureVersionOptions: [
        // {
        //   label: '二调地类图斑',
        //   value: '64309174-011a-11ee-8147-080058000005',
        //   id: '64309174-011a-11ee-8147-080058000005',
        //   versionName: 'DLTB_ED',
        //   versionCName: '二调地类图斑',
        //   versionSerial: 1,
        //   featureId: 'c9abd67f-5587-4a8e-b655-77e90d3a9e3c',
        // },
        // {
        //   label: '三调地类图斑',
        //   value: '79e5250c-011a-11ee-8148-080058000005',
        //   id: '79e5250c-011a-11ee-8148-080058000005',
        //   versionName: 'DLTB_SD',
        //   versionCName: '三调地类图斑',
        //   versionSerial: 2,
        //   featureId: 'c9abd67f-5587-4a8e-b655-77e90d3a9e3c',
        // },
      ],
      // 字段名称
      fieldAliasOptions: [
        // {
        //   label: '标识码',
        //   value: 'bsm',
        // },
        {
          label: '地类编码',
          value: 'dlbm',
        },
        // {
        //   label: '地类名称',
        //   value: 'dlmc',
        // },
        // {
        //   label: '图斑面积',
        //   value: 'tbmj',
        // },
      ],
      // 标准文档
      docStandardOptions: [
        // {
        //   label: '《第三次全国土地调查技术规程》',
        //   value: '1',
        // },
        // {
        //   label: '《2020国土变更调查技术规程》',
        //   value: '2',
        // },
        // {
        //   label: '《第二次全国土地调查技术规程》',
        //   value: '3',
        // },
      ],
      // 表格列配置
      tableColumns: [
        {
          key: 0,
          prop: 'id',
          align: 'center',
          label: '唯一标识',
          width: '160',
        },
        {
          key: 1,
          prop: 'key',
          align: 'center',
          label: '编码-key',
          width: '120',
        },
        {
          key: 2,
          prop: 'value',
          align: 'center',
          label: '名称-value',
          width: '120',
        },
        {
          key: 3,
          prop: 'domainOrder',
          align: 'center',
          label: '顺序号',
          width: '80',
        },
        {
          key: 4,
          prop: 'fieldName',
          align: 'center',
          label: '字段名',
          width: '120',
        },
        {
          key: 5,
          prop: 'fieldAlias',
          align: 'center',
          label: '字段别名',
          width: '120',
        },
        {
          key: 6,
          prop: 'businessType',
          align: 'center',
          label: '业务分组',
          width: '120',
        },
        {
          key: 7,
          prop: 'featureName',
          align: 'center',
          label: '要素名称',
          width: '120',
        },
        {
          key: 8,
          prop: 'featureVersion',
          align: 'center',
          label: '版本名称',
          width: '120',
        },
        {
          key: 9,
          prop: 'desc',
          align: 'center',
          label: '备注',
          minWidth: '200',
        },
      ],
      // 表格数据
      tableData: [],
      // 表格选中行
      rowsSelected: [],
      // 表单ref
      refFormName: 'FieldDomainForm',
      // 表单标题
      formDialogTitle: '',
      // 表单显隐
      formDialogVisible: false,
      // 默认的表单数据
      defaultForm: {
        id: null,
        key: '',
        value: '',
        businessType: '',
        fieldName: '',
        featureName: '',
        domainOrder: null,
        featureId: '',
        featureVersion: '',
        featureVersionId: '',
        docStandard: '',
        desc: '',
      },
      // 表单数据
      form: {
        id: null,
        key: '',
        value: '',
        businessType: '',
        fieldName: '',
        featureName: '',
        domainOrder: null,
        featureId: '',
        featureVersion: '',
        featureVersionId: '',
        docStandard: '',
        desc: '',
      },
      // 表单校验
      formRules: {
        key: [{ required: true, message: '请输入字段值编码', trigger: 'blur' }],
        value: [{ required: true, message: '请输入字段值名称', trigger: 'blur' }],
        businessType: [{ required: true, message: '请选择字段名称', trigger: 'blur' }],
        fieldName: [{ required: true, message: '请选择字段名称', trigger: 'blur' }],
        featureName: [{ required: true, message: '请选择要素名称', trigger: 'blur' }],
        featureVersionId: [{ required: true, message: '请选择要素版本', trigger: 'blur' }],
        domainOrder: [{ required: true, message: '请选择要素版本', trigger: 'blur' }],
      },
      // 文件上传组件参数
      refUploadFile: 'refUploadFile',
      upload: {
        url: '', // excel文件上传路径
        // disabled: false, // 上传组件是否可用-永不启用，为true的时候，已上传的文件无法删除
        accept: '.xlsx,.xls',
        limit: 1, // 上传的最大文件个数限制
        maxFielSize_M: 1, // 单个文件的限制大小（单位：M）
        fileList: [], // 上传的文件列表
      },
    };
  },
  mounted() {},
  methods: {
    /**
     * 获取表格数据
     */
    getList(queryParameters, callback) {
      const vm = this;
      if (JSON.stringify(vm.$route.query) !== '{}') {
        const refTable = vm.getRefDom('refResourceTable');
        if (refTable && vm.$route.query.hasOwnProperty('businessType')) {
          vm.runtimeSet(
            refTable,
            refTable.queryParameters,
            'businessType',
            vm.$route.query.businessType,
          );
        }
        if (refTable && vm.$route.query.hasOwnProperty('featureCName')) {
          vm.runtimeSet(
            refTable,
            refTable.queryParameters,
            'featureCName',
            vm.$route.query.featureCName,
          );
        }
        if (refTable && vm.$route.query.hasOwnProperty('versionCName')) {
          vm.runtimeSet(
            refTable,
            refTable.queryParameters,
            'versionCName',
            vm.$route.query.versionCName,
          );
        }
        if (refTable && vm.$route.query.hasOwnProperty('fieldAlias')) {
          vm.runtimeSet(
            refTable,
            refTable.queryParameters,
            'fieldAlias',
            vm.$route.query.fieldAlias,
          );
        }
      }
      const { businessType, featureCName, versionCName, fieldAlias, pageSize, page } =
        queryParameters;
      pageList({
        query: {
          page: page,
          pageSize: pageSize,
        },
        data: {
          businessType: !businessType ? null : businessType.trim(),
          versionCName: !versionCName ? null : versionCName.trim(),
          featureCName: !featureCName ? null : featureCName.trim(),
          fieldAlias: !fieldAlias ? null : fieldAlias.trim(),
        },
      })
        .then((res) => {
          if (res.status === 'success') {
            vm.ifLoading = false;
            const {
              data: { items, total },
            } = res;
            const tableData = items.map((item, index) => {
              const {
                id,
                domainKey,
                domainValue,
                fieldName,
                domainOrder,
                domainDesc,
                featureVersionId,
                createTime,
                updateTime,
                isDeleted,
                fieldAlias,
                fieldType,
                fieldLength,
                fieldPrecision,
                isNullable,
                isUnique,
                standardDocId,
                isStandard,
                canEnum,
                fieldOrder,
                versionName,
                versionCName,
                versionSerial,
                featureId,
                featureName,
                featureCName,
                isGeometry,
                geometryType,
                businessType,
                updateMethod,
                updateRate,
              } = item;
              return {
                id: id,
                key: domainKey,
                value: domainValue,
                domainOrder: domainOrder,
                fieldName: fieldName,
                fieldAlias: fieldAlias,
                businessType: businessType,
                featureName: featureCName,
                featureVersion: versionCName,
                desc: domainDesc,
                featureVersionId: featureVersionId,
                featureId: featureId,
                docStandard: standardDocId,
              };
            });
            const dataTotalCount = total;
            callback({
              items: tableData,
              total: dataTotalCount,
            });
          } else {
            vm.$message({
              type: 'error',
              message: res.message,
            });
          }
        })
        .catch((err) => {
          throw err;
        });
    },
    /**
     * 查询
     */
    handlerQuery() {
      const vm = this;
      const refResourceTable = vm.getRefDom('refResourceTable');
      if (refResourceTable) {
        refResourceTable.queryTable();
      }
    },
    /**
     * 添加数据
     */
    handlerAddNew() {
      const vm = this;
      vm.formDialogTitle = '新增要素字段值信息';
      vm.resetFormFields();
      vm.form.docStandard = '';
      vm.docStandardOptions = [];
      vm.formDialogVisible = true;
    },
    /**
     * 修改数据
     */
    handlerModify(row) {
      const vm = this;
      vm.formDialogTitle = '修改要素字段值信息';
      vm.resetFormFields();
      const versionCName = row.featureVersion;
      // 要素版本
      versionList({
        query: {
          page: 1,
          pageSize: 500,
        },
        data: {
          versionCName: row.featureVersion.trim(),
        },
      })
        .then((res) => {
          if (res.status === 'success') {
            vm.featureVersionOptions = res.data.items.map((item) => {
              const { id, versionName, versionCName, versionSerial, featureId } = item;
              return {
                id: id,
                label: versionCName,
                value: id,
                versionName: versionName,
                versionCName: versionCName,
                versionSerial: versionSerial,
                featureId: featureId,
              };
            });
            // 字段选项
            fieldList({
              query: {
                page: 1,
                pageSize: 100,
              },
              data: {
                versionCName: versionCName.trim(),
              },
            })
              .then((res) => {
                if (res.status === 'success') {
                  vm.ifLoading = false;
                  const {
                    data: { items },
                  } = res;
                  vm.fieldAliasOptions = items
                    .filter((item) => item.canEnum)
                    .map((item, index) => {
                      const { id, fieldName, fieldAlias, fieldType, fieldOrder } = item;
                      return {
                        id: id,
                        label: fieldAlias,
                        value: fieldName,
                        name: fieldName,
                        alias: fieldAlias,
                        type: fieldType,
                        order: fieldOrder,
                      };
                    });
                } else {
                  vm.$message({
                    type: 'error',
                    message: res.message,
                  });
                }
              })
              .catch((err) => {
                throw err;
              });
            // 规范、标准文档
            standardDocsList({
              query: {
                page: 1,
                pageSize: 1000000,
              },
              data: {
                versionCName: row.featureVersion.trim(),
              },
            })
              .then((res) => {
                if (res.status === 'success') {
                  const {
                    data: { items },
                  } = res;
                  vm.docStandardOptions = items.map((item) => {
                    const { id, docName, filePath, docStandardType, docDesc } = item;
                    return {
                      label: docName,
                      value: id,
                      id: id,
                      name: docName,
                      standardType: docStandardType,
                      path: filePath,
                      desc: docDesc,
                    };
                  });
                  vm.form = row;
                  vm.formDialogVisible = true;
                } else {
                  vm.$message({
                    type: 'error',
                    message: res.message,
                  });
                }
              })
              .catch((err) => {
                throw err;
              });
          } else {
            vm.$message.error(res.message);
          }
        })
        .catch((err) => {
          vm.$message.error(`要素版本或已删除，请检查版本：【${row.featureVersion}】是否存在`);
          throw err;
        });
    },
    /**
     * 删除数据
     */
    handlerDelete(row) {
      const vm = this;
      vm.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          deleteOne({
            query: {
              id: row.id,
            },
          })
            .then((res) => {
              if (res.status === 'success') {
                vm.$message({
                  type: 'success',
                  message: '删除成功!',
                });
                vm.handlerQuery();
              } else {
                vm.$message({
                  type: 'error',
                  message: res.message,
                });
              }
            })
            .catch((err) => {
              throw err;
            });
        })
        .catch(() => {
          vm.$message({
            type: 'info',
            message: '已取消删除',
          });
        });
    },
    /**
     * 批量删除
     */
    handlerDeleteBatch() {
      const vm = this;
      const rows = vm.rowsSelected;
      vm.$confirm('此操作将永久删除所选的多条记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          vm.$message({
            type: 'success',
            message: '删除成功!',
          });
          vm.handlerQuery();
        })
        .catch(() => {
          vm.$message({
            type: 'info',
            message: '已取消删除',
          });
        });
    },
    handlerInputValueChange(conditionName) {
      const vm = this;
      if (vm.$route.query && vm.$route.query.hasOwnProperty(conditionName)) {
        delete vm.$route.query[conditionName];
      }
    },
    /**
     * 检索条件清空
     */
    handlerClear(conditionName) {
      const vm = this;
      if (vm.$route.query && vm.$route.query.hasOwnProperty(conditionName)) {
        delete vm.$route.query[conditionName];
      }
      vm.handlerQuery();
    },
    /**
     * 提交审批信息
     */
    handlerSubmit(formName) {
      const vm = this;
      vm.$refs[formName].validate((valid) => {
        if (valid) {
          const {
            id,
            key,
            value,
            businessType,
            fieldName,
            featureName,
            featureId,
            featureVersion,
            domainOrder,
            featureVersionId,
            docStandard,
            desc,
          } = vm.form;
          const newFeature = {
            id: id,
            domainKey: key,
            domainValue: value,
            filedName: fieldName,
            domainOrder: Number(domainOrder),
            domainDesc: desc,
            featureVersionId: featureVersionId,
            standardDocId: !docStandard ? null : docStandard,
          };
          if (id === null) {
            newFeature.id = null;
            addOne({
              query: {},
              data: newFeature,
            })
              .then((res) => {
                if (res.status === 'success') {
                  // 新增
                  vm.$message.success('新增成功');
                  vm.dialogClose();
                } else {
                  vm.$message({
                    type: 'error',
                    message: res.message,
                  });
                }
              })
              .catch((err) => {
                throw err;
              });
          } else {
            // 修改
            updateOne({
              query: {},
              data: newFeature,
            })
              .then((res) => {
                if (res.status === 'success') {
                  vm.$message.success('修改成功');
                  vm.dialogClose();
                } else {
                  vm.$message({
                    type: 'error',
                    message: res.message,
                  });
                }
              })
              .catch((err) => {
                throw err;
              });
          }
        } else {
          vm.$message.error('请正确填写表单项');
          return false;
        }
      });
    },
    /**
     * 导入
     */
    handlerImportData() {
      const vm = this;
      const domUploadButton = vm.$refs.refUploadButton.$el;
      // 清除当前文件上传组件的文件列表
      const refUploadFile = vm.$refs[vm.refUploadFile];
      if (refUploadFile && domUploadButton) {
        vm.$nextTick(() => {
          refUploadFile.clearFiles();
          // vm.upload.accept = '.xlsx,.xls';
          vm.$nextTick(() => {
            domUploadButton.click();
          });
        });
      } else {
        vm.$message.error('上传组件失效，请联系管理员');
      }
    },
    /**
     * 上传的文件状态改变
     */
    uploadFileStateChange(file, fileList) {
      console.log('[uploadFileStateChange]:uploadFile', [file, fileList]);
    },
    /**
     * 已上传文件移除前事件
     */
    uploadFileBeforeRemove() {},
    /**
     * 移除已上传的文件
     */
    uploadFileRemove(file, fileList) {
      console.log('uploadFileRemove', [file, fileList]);
    },
    /**
     * 上传文件之前的钩子
     */
    uploadBeforeFile(file) {
      const vm = this;
      const fileSuffix = file.name.substring(file.name.lastIndexOf('.'));
      const whiteList = vm.upload.accept.split(',');
      whiteList.forEach((item) => item.trim());
      console.log('upload file type:', fileSuffix);
      console.log('upload file type whiteList:', whiteList);
      if (!whiteList.includes(fileSuffix)) {
        vm.$message({
          type: 'error',
          message: `仅支持上传${whiteList.join(', ')}格式`,
        });
        return false;
      }
      const limitFileSize = vm.upload.maxFielSize_M;
      const isLtFileSize = file.size / 1024 / 1024 < limitFileSize;
      if (!isLtFileSize) {
        vm.$message({
          type: 'error',
          message: `上传的文件大小不能超过 ${limitFileSize}MB`,
        });
        return false;
      }
      console.log('即将上传的文件', vm.upload.fileList);
      return true;
    },
    /**
     * 文件超出个数限制时的钩子
     */
    uploadFileExceed() {
      const vm = this;
      vm.$message({
        type: 'warning',
        message: '仅支持上传1个excel文件，请先移除已上传的excel文件',
      });
    },
    /**
     * 文件上传成功时的钩子
     */
    uploadFileSuccess(response) {
      const vm = this;
      if (response.status === 'success') {
        const refUploadFile = vm.$refs[vm.refUploadFile];
        if (refUploadFile) {
          vm.$nextTick(() => {
            refUploadFile.clearFiles();
          });
        }
      } else {
        vm.$message({
          type: 'error',
          message: response.message,
        });
      }
    },
    /**
     * excel文件上传
     */
    async httpUpload(httpRequest) {
      const vm = this;
      const file = httpRequest.file;
      if (!file) {
        vm.$message.error('请先上传excel文件');
        return;
      }
      const formData = new FormData();
      formData.append('file', file);
      const res = await importBatchData(formData);
      if (res.status === 'success') {
        vm.$message.success('导入成功');
      } else {
        vm.$message.error(res.message);
      }
      vm.dialogClose();
    },
    /**
     * 表格多选事件
     */
    rowSelectionChange(rows) {
      const vm = this;
      vm.rowsSelected = rows;
    },
    /**
     * 检索条件清空
     */
    handlerClear(conditionName) {
      const vm = this;
      if (vm.$route.query && vm.$route.query.hasOwnProperty(conditionName)) {
        vm.$route.query[conditionName] = null;
      }
      vm.handlerQuery();
    },
    /**
     * 弹窗关闭
     */
    dialogClose() {
      const vm = this;
      vm.resetFormFields();
      vm.formDialogVisible = false;
      vm.handlerQuery();
    },
    /**
     * 取消提交
     */
    handlerCancel() {
      const vm = this;
      vm.dialogClose();
    },
    /**
     * 根据ref获取dom元素
     */
    getRefDom(refName) {
      const vm = this;
      return vm.$refs[refName];
    },
    /**
     * 重置表单字段并清空非法校验
     */
    resetFormFields() {
      const vm = this;
      const elForm = vm.$refs[vm.refFormName];
      if (elForm) {
        elForm.clearValidate();
      }
      vm.form = JSON.parse(JSON.stringify(vm.defaultForm));
    },
    /**
     * 数据标准版本
     */
    handlerFeatureVersionManage(row) {
      const vm = this;
      vm.$router.push({
        path: `/data-standard/feature-version`,
        query: {
          businessType: row.businessType,
          featureCName: row.featureName,
          versionCName: row.featureVersion,
        },
      });
    },
    checkIFNum(key, val) {
      const vm = this;
      if (['', null].includes(val)) {
        return;
      }
      const isNum = val
        .split('')
        .every((c) => ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'].includes(c));
      if (!isNum) {
        vm.$message.warning('只能输入数字');
        if (isNaN(parseInt(val))) {
          vm.form[key] = null;
          return;
        }
      }
      vm.form[key] = `${parseInt(val)}`;
    },
    runtimeSet(refNode, obj, propName, propValue) {
      refNode.$set(obj, propName, propValue);
    },
    /**
     * 远程搜索要素信息
     */
    remoteGetVersionsOptions(keyword) {
      const vm = this;
      if (!keyword || !keyword.trim()) {
        vm.featureVersionOptions = [];
        return;
      }
      versionList({
        query: {
          page: 1,
          pageSize: 500,
        },
        data: {
          versionCName: keyword.trim(),
        },
      })
        .then((res) => {
          if (res.status === 'success') {
            vm.featureVersionOptions = res.data.items.map((item) => {
              const {
                id,
                versionName,
                versionCName,
                versionSerial,
                isLatestVersion,
                versionDesc,
                featureId,
                createTime,
                updateTime,
                isDeleted,
                featureName,
                featureCName,
                isGeometry,
                geometryType,
                businessType,
                updateMethod,
                updateRate,
                featureDesc,
              } = item;
              return {
                id: id,
                label: versionCName,
                value: id,
                versionName: versionName,
                versionCName: versionCName,
                versionSerial: versionSerial,
                featureId: featureId,
              };
            });
          } else {
            vm.$message.error(res.message);
          }
        })
        .catch((err) => {
          throw err;
        });
    },
    /**
     * 选中的版本改变
     */
    handlerVersionChange(val) {
      const vm = this;
      const versionSelected = vm.featureVersionOptions.find((item) => item.id === val);
      if (!versionSelected) {
        vm.$message.info('未找到该版本，请检查改版本是否已被删除');
        return;
      }
      vm.fieldAliasOptions = [];
      vm.form.fieldName = '';
      const { versionCName } = versionSelected;
      fieldList({
        query: {
          page: 1,
          pageSize: 100,
        },
        data: {
          versionCName: versionCName.trim(),
        },
      })
        .then((res) => {
          if (res.status === 'success') {
            vm.ifLoading = false;
            const {
              data: { items, total },
            } = res;
            vm.fieldAliasOptions = items
              .filter((item) => item.canEnum)
              .map((item, index) => {
                const {
                  id,
                  fieldName,
                  fieldAlias,
                  fieldType,
                  fieldLength,
                  fieldPrecision,
                  isNullable,
                  isUnique,
                  isStandard,
                  canEnum,
                  fieldOrder,
                  fieldDesc,
                  featureVersionId,
                  createTime,
                  updateTime,
                  isDeleted,
                  versionName,
                  versionCName,
                  versionSerial,
                  featureId,
                  featureName,
                  featureCName,
                  isGeometry,
                  geometryType,
                  businessType,
                  updateMethod,
                  updateRate,
                } = item;
                return {
                  id: id,
                  label: fieldAlias,
                  value: fieldName,
                  name: fieldName,
                  alias: fieldAlias,
                  type: fieldType,
                  order: fieldOrder,
                };
              });
          } else {
            vm.$message({
              type: 'error',
              message: res.message,
            });
          }
        })
        .catch((err) => {
          throw err;
        });
      standardDocsList({
        query: {
          page: 1,
          pageSize: 1000000,
        },
        data: {
          versionCName: !versionCName ? null : versionCName.trim(),
        },
      })
        .then((res) => {
          if (res.status === 'success') {
            const {
              data: { items },
            } = res;
            vm.form.docStandard = '';
            vm.docStandardOptions = items.map((item) => {
              const { id, docName, filePath, docStandardType, docDesc } = item;
              return {
                label: docName,
                value: id,
                id: id,
                name: docName,
                standardType: docStandardType,
                path: filePath,
                desc: docDesc,
              };
            });
          } else {
            vm.$message({
              type: 'error',
              message: res.message,
            });
          }
        })
        .catch((err) => {
          throw err;
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.feature-version__container {
  height: calc(100vh - 85px);
  overflow: hidden;
  background-color: #f2f2f2;
  .content {
    width: 100%;
    height: 100%;
    overflow: hidden;
    background-color: rgba(255, 255, 255, 1);
    padding: 15px;
    display: flex;
    flex: 1;
    flex-direction: column;
    .panel-header {
      height: 40px;
    }
    .panel-content {
      flex: 1;
      height: calc(100% - 80px);
      padding: 12px 0;
    }
    .panel-footer {
      height: 40px;
    }
  }

  .search-conditions {
    display: flex;
    flex-direction: column;
    font-size: small;
    .condition-item {
      display: flex;
      align-items: center;
      margin-bottom: 15px;
      .item-label {
        width: 206px;
        text-align: right;
        padding-right: 10px;
      }
      .item-value {
        flex: 1;
      }
    }
  }

  .search-func {
    padding: 0px 10px;
    .btn-query {
      display: inline-block;
      width: 50%;
      padding-right: 10px;
    }
    .btn-reset {
      display: inline-block;
      width: 50%;
      padding-left: 10px;
    }
  }

  .panel-header {
    .table-func {
      width: 28%;
      .table-func-btn {
        display: inline-block;
        padding: 0px 10px;
        width: 25%;
      }
      .btn-add {
        padding-left: 0px;
      }
    }
  }

  .panel-content {
    ::v-deep .table-head-cell-style {
      text-align: center !important;
      color: rgba(100, 100, 100);
    }
    ::v-deep .table-head-cell-style {
      color: rgb(0, 0, 0);
      background: rgb(215, 215, 215);
    }
  }

  .panel-footer {
    display: flex;
    align-items: flex-end;
  }

  .btn-action {
    width: 100%;
    .btn-modify {
      display: inline-block;
      width: 50%;
      padding: 0px 10px;
    }
    .btn-approval {
      display: inline-block;
      width: 50%;
      padding: 0px 10px;
    }
  }

  // 临时
  .table-panel {
    width: 100%;
    height: 100%;
    overflow: hidden;
    background-color: rgba(255, 255, 255, 1);
    // padding: 15px 10px;
  }

  .form-dialog {
    ::v-deep .el-dialog__header {
      text-align: center;
    }
    ::v-deep .el-dialog__body {
      padding: 20px !important;
      padding-top: 5px !important;
    }
    ::v-deep .normal-table-header-cell {
      color: rgb(0, 0, 0);
      background: rgb(215, 215, 215);
      font-weight: bold;
    }
  }

  ::v-deep .normal-table-header-cell {
    color: rgb(0, 0, 0);
    background: rgb(215, 215, 215);
    font-weight: bold;
  }

  .btn-list {
    .btn-item {
      display: inline-block;
      .el-button {
        // background: #169bd5;
        // border-color: #169bd5;
      }
    }
  }
  ::v-deep .header-search-button {
    // background: #169bd5;
    // border-color: #169bd5;
  }
  ::v-deep .col-btn-item {
    display: none;
  }
}

.form-dialog {
  .form-panel {
    height: 100%;
    width: 100%;
    display: flex;
    flex-direction: column;
  }
  .approval-list {
    flex: 1;
    display: flex;
    flex-direction: column;
    .approval-list-item {
      height: 40px;
      line-height: 40px;
      flex: 1;
      display: flex;
      .label {
        width: 13%;
        text-align: center;
      }
      .value {
        flex: 1;
      }
    }
    .permission-approval {
      height: 40px;
      line-height: 40px;
    }
  }
  .approval-action {
    height: 60px;
    line-height: 60px;
    text-align: center;
    .btn-submit {
      width: 150px;
      background: #169bd5;
      border-color: #169bd5;
    }
  }

  ::v-deep .el-dialog__body {
    padding-bottom: 10px;
  }
}

.filter-conditions {
  .filter-item {
    display: inline-block;
    .el-button {
      background: #169bd5;
      border-color: #169bd5;
    }
  }
}

.form-item {
  width: 100%;
}
</style>
